{% extends "base.html" %}
{% load extra_filters %}
{% load timezone_filters %}

{% block title %}{{site_name}}: Activity {{ activity.name }}{% endblock %}

{% block extra_head %}
<script type="text/javascript" src="/static/jquery.inplace.pack.js"></script>

<script src="/static/timeplot_ajax/simile-ajax-api.js" type="text/javascript"></script>
<script type="text/javascript">
  Timeline_urlPrefix='/static/timeplot_js/';
  Timeline_parameters='bundle=true';
  Timeplot_urlPrefix='/static/timeplot_js/';
  Timeplot_parameters='bundle=true';
  SimileAjax.History['enabled'] = false;
</script>

<script type="text/javascript" src="/static/timeplot_js/timeline-api.js"></script>
<script type="text/javascript" src="/static/timeplot_js/timeplot-api.js"></script>
{% endblock %}


{% block content %}
<table width="100%">
  <tr>
    <td align="left" valign="top" width="50%">
        <div id="activity_table">
          <div id="activitySummaryDataComponent" class="activityComponent">
            <div id="activitySummaryTitle">
              Summary for <span id="editable_name">{{activity.name}}</span>:
                    {% if show_locations %}
              <a onclick="delete_activity('{{ activity.key.id }}')">delete</a>
                    <script type="text/javascript">
                      $("#editable_name").editInPlace({
                      url: "/a/" + {{activity.key.id}},
                      params: "ajax=yes",
                      value_required: true,
                      params: "activity_id={{activity.key.id}}&attribute=name"
                      });
                    </script>
                    {% endif %}
            </div>

            <div class="activity-summary-table">
              <table id>
                <tr>
                  <td width="120">
                    Start Time
                  </td>
                  <td>
                    {{ activity.start_time|localtime:activity.user.get_profile.timezone }}
                  </td>
                </tr>

                <tr>
                  <td>
                    End Time
                  </td>
                  <td>
                    {{ activity.end_time|localtime:activity.user.get_profile.timezone }}
                  </td>
                </tr>

                <tr>
                  <td>
                    Total Time
                  </td>
                  <td>
                    {{ activity.total_time|seconds_to_human_readable }} (Rolling: {{ activity.rolling_time|seconds_to_human_readable }})
                  </td>
                </tr>


                <tr>
                  <td>
                    Distance
                  </td>
                  <td>
                    {{ activity.total_meters|meters_to_prefered_distance:use_imperial }} {{use_imperial|miles_or_km_units}}
                  </td>
                </tr>


                <tr>
                  <td>
                    Ascent
                  </td>
                  <td>
                    {{activity.total_ascent|format_meters:use_imperial}} {{use_imperial|meters_or_feet_units}}
                  </td>
                </tr>


                <tr>
                  <td>
                    Speed
                  </td>
                  <td>
                    Avg: {{ activity.average_speed|kph_to_prefered_speed:use_imperial }} {{use_imperial|mph_or_kph_units}}, Max: {{ activity.maximum_speed|kph_to_prefered_speed:use_imperial }} {{use_imperial|mph_or_kph_units}}
                  </td>
                </tr>


                <tr>
                  <td>
                    Heart Rate:
                  </td>
                  <td>
                    Avg: {{ activity.average_bpm }}, Max: {{ activity.maximum_bpm }} bpm
                  </td>
                </tr>

                <tr>
                  <td>
                    Cadence
                  </td>
                  <td>
                    Avg: {{ activity.average_cadence }}, Max: {{ activity.maximum_cadence }} rpm
                  </td>
                </tr>

                <tr>
                  <td>
                    Power
                  </td>
                  <td>
                    Avg: {{ activity.average_power }}, Max: {{ activity.maximum_power }} Watts
                  </td>
                </tr>

                <tr>
                  <td>
                    Calories
                  </td>
                  <td>
                    {{ activity.total_calories|floatformat:"-2" }}
                  </td>
                </tr>
                {% if show_locations %}
                <tr>
                  <td>
                    Start Location
                  </td>
                  <td id="start_location">
                  </td>
                </tr>

                <tr>
                  <td>
                    Mid Location
                  </td>
                  <td id="mid_location">
                  </td>
                </tr>

                <tr>
                  <td>
                    End Location
                  </td>
                  <td id="end_location">
                  </td>
                </tr>
                {% endif %}

                <tr>
                  <td>
                    Uploaded By
                  </td>
                  <td>
                    {{ activity.user.user }}
                  </td>
                </tr>
                <tr>
                  <td>
                    Public:
                  </td>
                  <td>
                    <span class="summaryField" id="public_flag">{{ activity.public }}</span>
                    {% if show_locations %}
                    <script type="text/javascript">
                      $("#public_flag").editInPlace({
                      url: "/a/"+{{activity.key.id}},
                      value_required: true,
                      field_type: "select",
                      select_options: "True, False",
                      params: "ajax=yes&attribute=public",
                      success: function(html, original_element){
                      if(html == 'False'){
                        $("#public_update").html('Set this activity to public to share it.')
                      } else {
                        $("#public_update").html('<a href="http://maps.google.com/maps?q={{kml_location}}&t=p">Bigger Map</a> - <a href="{% url activity_public activity.key.id %}">Public Link</a>');
                      }
                        return(html);
                      },
                      });
                    </script>
                    {% endif %}

                  </td>
                </tr>

                <tr>
                  <td>
                    Comment:
                  </td>
                  <td>
                    <span class="summaryField" id="editable_comment">{{ activity.comment }}</span>
                    {% if show_locations %}
                    <script type="text/javascript">
                      $("#editable_comment").editInPlace({
                      url: "/a/" + {{activity.key.id}},
                      params: "ajax=yes",
                      value_required: true,
                      params: "activity_id={{activity.key.id}}&attribute=comment"
                      });
                    </script>
                    {% endif %}
                  </td>
                </tr>
                <tr>
                  <td>
                    Tags:
                  </td>
                  <td>
                    <span class="summaryField" id="editable_tags">{{ activity.tags|join:", "}}</span>
                    {% if show_locations %}
                    <script type="text/javascript">
                      $("#editable_tags").editInPlace({
                      url: "/a/" + {{activity.key.id}},
                      params: "ajax=yes",
                      params: "activity_id={{activity.key.id}}&attribute=tags"
                      });
                    </script>
                    {% endif %}
                  </td>
                </tr>
                {% if activity.sourcedatafile_set.get.parse_errors %}
                <tr>
                  <td>
                    Parse Errors:
                  </td>
                  <td>
                    {% for e in activity.sourcedatafile_set.get.parse_errors %}
                    {{e}}</br>
                    {% endfor %}
                  </td>
                </tr>
                {% endif %}

              </table>
            </div>
          </div>
        </div>
    </td>
    <td>
      <div id="map" style="width: 100%; height: 400px"></div>
      <div>
        <a href="{% url activity_kml activity.key.id %}">Download KML</a> -
        <a href="{% url activity_source activity.key.id %}">Source File</a> -
        <span id="public_update">
        {% if activity.public %}
        <a href="http://maps.google.com/maps?q={{kml_location}}&t=p">Bigger Map</a> -
        <a href="{% url activity_public activity.key.id %}">Public Link</a>
        {% else %}
        Set this activity to public to share it.
        {% endif %}
      </span>
      </div>
    </td>
  </tr>
  <tr>
    <td valign="top" colspan="2">
      <span class="redlabel">Altitude</span> ({{use_imperial|meters_or_feet_units}}) vs <span class="bluelabel">Distance</span> ({{use_imperial|miles_or_km_units}}):
      <div id="altitudechart" style="width: 920px; height: 200px"></div>
      <span class="redlabel">Cadence</span> (RPM) vs <span class="bluelabel">Speed</span> ({{use_imperial|mph_or_kph_units}}):
      <div id="speedchart" style="width: 920px; height: 200px"></div>
      <span class="redlabel">Heart Rate</span> (BPM) vs <span class="bluelabel">Power</span> (Watts):
      <div id="bpmchart" style="width: 920px; height: 200px"></div>
    </td>
  </tr>
</table>
</div>

<br/>

<script type="text/javascript">
  google.load("maps", "2.x");

  function showAddress(response, element_id) {
    if (!response || response.Status.code != 200) {
      document.getElementById(element_id).innerHTML = "Couldn't Reverse Geocode.  Error: " + response.Status.code;
    } else {
      place = response.Placemark[0];
      document.getElementById(element_id).innerHTML = place.address;
    }
  }

  function initialize() {
    var map = new google.maps.Map2(document.getElementById("map"));
    map.setMapType(G_PHYSICAL_MAP);
    map.setCenter(new google.maps.LatLng(0,0),0);
    var sw = new google.maps.LatLng({{activity.sw_point}});
    var ne = new google.maps.LatLng({{activity.ne_point}});
    var bounds = new google.maps.LatLngBounds(sw, ne);
    var mapZoomLevel = map.getBoundsZoomLevel(bounds);
    var mapCenter = bounds.getCenter();
    map.setCenter(mapCenter, mapZoomLevel);

    var polyline1_1 = new google.maps.Polyline.fromEncoded({
      weight: 4,
      opacity: 0.6,
      points: {{pts|safe}},
      levels: {{levs|safe}},
      zoomFactor: 2,
      numLevels: 18
    });
    map.addOverlay(polyline1_1);
    map.addControl(new google.maps.SmallMapControl());
    {% if show_locations %}

    var start_point = new GLatLng({{ activity.start_point }});
    var mid_point = new GLatLng({{ activity.mid_point }});
    var end_point = new GLatLng({{ activity.end_point }});
    geocoder = new google.maps.ClientGeocoder();

    geocoder.getLocations(start_point,
      function(response) {
        showAddress(response, 'start_location');
      }
      );
    geocoder.getLocations(mid_point,
      function(response) {
        showAddress(response, 'mid_location');
      }
      );
    geocoder.getLocations(end_point,
      function(response) {
      showAddress(response, 'end_location');
      }
      );
    {% endif %}
  }
  google.setOnLoadCallback(initialize);

  function drawGraphs() {
    var eventSource = new Timeplot.DefaultEventSource();

    var timeGeometry = new Timeplot.DefaultTimeGeometry({
      gridColor: new Timeplot.Color("#000000"),
      axisLabelsPlacement: "bottom"
    });

    var altitudeGeometry = new Timeplot.DefaultValueGeometry({
      gridColor: "#48992C",
      axisLabelsPlacement: "left",
    });
    var distanceGeometry = new Timeplot.DefaultValueGeometry({
      gridColor: "#3291EB",
      axisLabelsPlacement: "right",
      min: 0,
      });


    var cadenceGeometry = new Timeplot.DefaultValueGeometry({
      gridColor: "#48992C",
      axisLabelsPlacement: "left",
      min: 0,
      });
    var speedGeometry = new Timeplot.DefaultValueGeometry({
      gridColor: "#3291EB",
      axisLabelsPlacement: "right",
      min: 0,
      });

    var bpmGeometry = new Timeplot.DefaultValueGeometry({
      gridColor: "#48992C",
      axisLabelsPlacement: "left",
      min: 0,
    });
    var powerGeometry = new Timeplot.DefaultValueGeometry({
      gridColor: "#3291EB",
      axisLabelsPlacement: "right",
      min: 0,
    });
    var altitudeInfo = [
      Timeplot.createPlotInfo({
        id: "altitude_plot",
        dataSource: new Timeplot.ColumnSource(eventSource,1),
        valueGeometry: altitudeGeometry,
        timeGeometry: timeGeometry,
        lineColor: "#48992C",
        fillColor: "#DCECD7",
        showValues: true
        }),
      Timeplot.createPlotInfo({
        id: "distance_plot",
        dataSource: new Timeplot.ColumnSource(eventSource,4),
        valueGeometry: distanceGeometry,
        timeGeometry: timeGeometry,
        lineColor: "#3291EB",
        showValues: true
      }),
      ];
    var speedInfo = [
      Timeplot.createPlotInfo({
        id: "cadence_plot",
        dataSource: new Timeplot.Processor(
          new Timeplot.ColumnSource(eventSource,3),
            Timeplot.Operator.average, { size: 30 }),
        valueGeometry: cadenceGeometry,
        timeGeometry: timeGeometry,
        lineColor: "#48992C",
        fillColor: "#DCECD7",
        showValues: true
        }),

      Timeplot.createPlotInfo({
        id: "speed_plot",
        dataSource: new Timeplot.Processor(
          new Timeplot.ColumnSource(eventSource,2),
            Timeplot.Operator.average, { size: 5 }),
        valueGeometry: speedGeometry,
        timeGeometry: timeGeometry,
        lineColor: "#3291EB",
        showValues: true
        }),

      ];
    var bpmInfo = [
      Timeplot.createPlotInfo({
        id: "bpm_plot",
        dataSource: new Timeplot.Processor(
          new Timeplot.ColumnSource(eventSource,5),
            Timeplot.Operator.average, { size: 15 }),
        valueGeometry: bpmGeometry,
        timeGeometry: timeGeometry,
        lineColor: "#48992C",
        fillColor: "#DCECD7",
        showValues: true
        }),

      Timeplot.createPlotInfo({
        id: "power_plot",
        dataSource: new Timeplot.Processor(
          new Timeplot.ColumnSource(eventSource,6),
            Timeplot.Operator.average, { size: 15 }),
        valueGeometry: powerGeometry,
        timeGeometry: timeGeometry,
        lineColor: "#0000FF",
        showValues: true
        }),

    ];

    altitudeplot = Timeplot.create(document.getElementById("altitudechart"),
        altitudeInfo);
    speedplot = Timeplot.create(document.getElementById("speedchart"),
        speedInfo);
    bpmplot = Timeplot.create(document.getElementById("bpmchart"),
        bpmInfo);

    var activity_data = {{data|safe}};
    eventSource.loadText(activity_data.join('\n'), ',', document.location.href);
  };
google.setOnLoadCallback(drawGraphs);

function delete_activity(id) {
  if (confirm('Are you sure?'))
  {
  $.ajax({
      url: '/a/' + id + '.delete',
      type: 'POST',
      timeout: 4000,
      data: {'activity_id':id},
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('Error Deleting Activity ' + id +': ' + textStatus)
      },
      success: function(response){
        window.location = "/a/"
      }
  });
  }
};

</script>


{% endblock %}
